<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Authentication extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		$this->load->model('authentication_model');
		$this->load->helper(array('form', 'url'));
	}
	
	function index()
	{
		
	}
	// Validate the user can login
	function login(){
		// Now we verify the result
		if( $this->authentication_model->validate() == TRUE ){
			// If user did validate,
			// Send them to members area
			redirect('/home');
		}else{
			// If user did not validate, then show them login page again
			$msg = '<font color=red>Invalid username and/or password.</font><br />';
			$data['msg'] = $msg;
			$this->load->view('welcome_view', $data);
		}
		
	}
	
	function signup()
	{		
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
		$this->form_validation->set_rules('nombre', 'nombre', 'required|min_length[3]|max_length[12]|trim');
		$this->form_validation->set_rules('apellido', 'apellido', 'required|min_length[3]|max_length[100]|trim');
		//$this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[100]|callback_username_check|trim');
		$this->form_validation->set_rules('username', 'username', 'callback_username_check');
		$this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
		$this->form_validation->set_rules('correo', 'correo', 'required|valid_email|trim');		
		//$this->load->view('header');
		//Valida si es correcto el formulario
		if( $this->form_validation->run() == TRUE )
		{		
			if( $this->authentication_model->save_user() == TRUE ){
				// If user did validate,
				// Send them to members area
				redirect('/home/index');
			}else{
				// If user did not saved, then show them welcome  page again
				redirect('/welcome');
			}
			
		}
		else
		{
			$this->load->view('welcome_view');
		}		
	}
	
	/**
	 * Valida si existe registrado el username, para evitar el registro de usuarios repetidos 
	 * @return boolean
	 */
	public  function username_check(){
		if ( $this->authentication_model->existing_user() == TRUE )
		{
			$this->form_validation->set_message('username_check', 'El username ya se encuentra registrado');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}
	
	function logout(){
		$this->session->sess_destroy();
		redirect('/welcome');
	}
}

?>